<?php
namespace app\farm\model;

use app\BaseModel;
use app\farm\model\User;
use app\farm\server\Land;
use app\farm\model\BalanceWater;
use app\shop\model\DistributionCash;
use app\shop\model\IntegralLog;
use app\publics\model\TmplConfig;
use longbingcore\wxcore\PushMsgModel;
use longbingcore\wxcore\WxTmpl;
use think\facade\Db;

class LandOrder extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_land_order';



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);;

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-21 17:04
     * @功能说明:下单支付信息
     */
    public function payOrderInfo($input){

        $spe_model     = new LandSpe();

        $massif_model  = new Massif();

        $seed_model    = new Seed();

        $land_model    = new LandList();

        $text_model    = new LandText();

        $data['land'] = $land_model->dataInfo(['id'=>$input['land_id']]);

        if(empty($data['land'])){

            return ['code'=>500,'msg'=>'该土地已下架'];

        }

        $dis = [

            'land_id' => $input['land_id'],

            'spe_id'  => $input['spe_id']
        ];

        $find = $this->where($dis)->where('pay_type','>=',1)->find();

        if(!empty($find)){

            return ['code'=>500,'msg'=>'该规格已被预约'];

        }
        //规格
        $spe = $spe_model->dataInfo(['id'=>$input['spe_id']]);

        if(empty($spe)){

            return ['code'=>500,'msg'=>'该规格已下架'];
        }
        $data['spe'] = $spe;
        //地块
        $massif = $massif_model->dataInfo(['id'=>$input['massif_id']]);

        if(empty($massif)){

            return ['code'=>500,'msg'=>'该地块已下架'];
        }

        $data['land_price'] = $spe['price'];

        $data['cycle']      = $input['cycle'];

        $data['total_massif_price'] = round($input['cycle']*$massif['price'],2);

        $data['massif'] = $massif;

        $data['seed_price'] = 0;

        if(!empty($input['seed_data'])){

            foreach ($input['seed_data'] as $v){

                $seed = $seed_model->dataInfo(['id'=>$v['id']]);

                if(empty($seed)){

                    return ['code'=>500,'msg'=>'该种子已下架'];
                }
                //溯源id
                $seed['source_id'] =  $text_model->where(['land_id'=>$input['land_id'],'type'=>2,'obj_id'=>$v['id']])->value('source_id');

                $seed['num'] = $v['num'];

                $data['seed_price'] += $seed['seed_price']*$v['num'];

                $data['seed'][] = $seed;

            }

        }

        $data['seed_price'] = round($data['seed_price'],2);
        //支付价格
        $data['pay_price'] = round($data['land_price']+$data['total_massif_price']+$data['seed_price'],2);

        $pay_price = $data['init_price'] = $data['pay_price'];

        if(!empty($input['coupon_id'])){

            $coupon_record_model = new CouponRecord();

            $coupon = $coupon_record_model->dataInfo(['id'=>$input['coupon_id'],'is_land'=>1,'status'=>1]);

            if(!empty($coupon)&&$coupon['full']<=$data['pay_price']){

                $data['pay_price'] -= $coupon['discount'];

            }else{

                $coupon = [];
            }

        }

        $data['land_price'] = $data['land_price']>0?$data['land_price']:0;

        $data['land_price'] = round($data['land_price'],2);

        $data['coupon_discount'] = !empty($coupon)?$coupon['discount']:0;

        $data['coupon_discount'] = $data['coupon_discount']<$pay_price?$data['coupon_discount']:$pay_price;

        $data['coupon_discount'] = round($data['coupon_discount'],2);

        $data['coupon_id'] = !empty($coupon)?$coupon['id']:0;

        return $data;
    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page=10){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-16 15:39
     * @功能说明:毁掉
     */
    public function orderResult($order_code,$transaction_id){

        $order = $this->dataInfo(['order_code'=>$order_code]);

        if(!empty($order)&&$order['pay_type']==1){

            Db::startTrans();

            $update = [

                'pay_time' => time(),

                'pay_type' => 2,

                'transaction_id' => $transaction_id
            ];

            $this->dataUpdate(['id'=>$order['id']],$update);
            //扣除余额
            if($order['balance']>0){

                $water_model = new \app\farm\model\BalanceWater();

                $res = $water_model->addWater($order,6,0);

                if($res==0){

                    Db::rollback();

                }
            }
            //添加流水
            $water_model = new FinanceWater();

            $water_model->addWater($order['id'],3,1,1);
            //分销
            $cash_model = new DistributionCash();

            $cash_model->addUserCash($order,2);

            Db::commit();

            $order['pay_time'] = $update['pay_time'];
            //发送订阅消息
            $this->paySendService($order);

            $sys_model = new PushMsgModel($order['uniacid']);

            $sys_model->sendMsg($order,5);

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2019-12-27 19:19
     * @功能说明:发送订阅消息
     */
    public function paySendService($order){

        $user_model = new User();
        //获取用户的open_id
        $openid = $user_model->where(['id'=>$order['user_id']])->value('openid');
        //访问页面
        $page = 'land/pages/order/detail?id='.$order['id'].'&notice=1';
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $tmpl       = $tmpl_model->where(['uniacid'=>$order['uniacid'],'tmpl_name'=>'land_order'])->find();
        //如果未添加模版消息 则不发送
        if(empty($tmpl)){
            return true;
        }else{
            $tmpl = $tmpl->toArray();
        }
        //模版id
        $tmpl_id = $tmpl['tmpl_id'];
        //模版类容
        $service_model = new WxTmpl($order['uniacid']);
        //模版的key
        $key_worlds    = $service_model::getTmplKey($tmpl_id);

        if(!empty($openid)&&!empty($tmpl_id)&&!empty($key_worlds)){
            //验证模版内容
            if(!is_array($key_worlds)||count($key_worlds)<4){

                return true;
            }

            $seed_model = new LandOrderSeed();

            $seed_name = $seed_model->where(['order_id'=>$order['id']])->column('title');

            $seed_name = !empty($seed_name)?implode(',',$seed_name):'';

            $order['goods_name'] = mb_substr($order['goods_name'],0,10);

            $seed_name = mb_substr($seed_name,0,10);
            //发送内容
            $send_data = array(

                $key_worlds[1]=>array(
                    //商品名称
                    'value'=> $order['order_code'],
                ),
                $key_worlds[2]=>array(
                    //种子明显
                    'value'=> $order['goods_name'],
                ),
                $key_worlds[3]=>array(
                    //支付金额
                    'value'=>!empty($seed_name)?$seed_name:'无',
                ),
                $key_worlds[4]=>array(
                    //商品价格
                    'value'=>$order['pay_price'].'元',

                ),
                $key_worlds[5]=>array(
                    //支付时间
                    'value'=>date('Y-m-d H:i:s',$order['pay_time']),
                ),
            );

          //  dump($send_data);exit;
            //模版消息库类
            $tmpl_sever = new WxTmpl($order['uniacid']);
            //发送模版消息
            $res = $tmpl_sever::sendTmpl($openid,$tmpl_id,$send_data,$page);

        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:超时自动退款
     */
    public function autoCancelOrder($uniacid,$user_id=0){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['pay_type','=',1];

        $dis[] = ['over_time','<',time()];

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];
        }

        $order = $this->where($dis)->select()->toArray();

        if(!empty($order)){

            foreach ($order as $value){

                $this->cancelOrder($value);

            }

        }

        return true;
    }



    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:退款
     */
    public function cancelOrder($order){

        Db::startTrans();

        $res = $this->dataUpdate(['id'=>$order['id'],'pay_type'=>1],['pay_type'=>-1]);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'取消失败'];
        }

        $land_model = new LandList();

        $land_model->where(['id'=>$order['land_id']])->update(['sale_num'=>Db::Raw('sale_num-1')]);

        Db::commit();

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-14 09:55
     * @功能说明:修改到期订单的状态
     */
    public function orderInit($user_id=0){

        $dis[] = ['pay_type','=',2];

        $dis[] = ['end_time','<',time()];

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];
        }

        $list = $this->where($dis)->select()->toArray();

        $integral_model = new IntegralLog();

        $distributionCash_model = new DistributionCash();

        if(!empty($list)){

            foreach ($list as $value){

                Db::startTrans();

                $update = [

                    'pay_type' => 7
                ];

                $this->dataUpdate(['id'=>$value['id']],$update);
                //添加积分
                $integral_model->integralUserAdd($value['user_id'],$value['get_integral'],$value['uniacid'],2,4,$value['id'],0,$value);
                //分销
                $res = $distributionCash_model->cashArrival($value,2);

                if($res==false){

                    Db::rollback();
                }

                Db::commit();

            }

        }

        return true;

    }


    /**
     * @param $dis
     * @param int $page
     * @功能说明:后台下单列表
     * @author chenniang
     * @DataTime: 2022-02-16 14:05
     */
    public function adminDataList($dis,$page=10){

        $data = $this->alias('a')
            ->join('lbfarm_order_address b','a.id = b.order_id AND b.type=1','left')
            ->where($dis)
            ->field('a.*,b.user_name,b.mobile')
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;
    }


    /**
     * @param $dis
     * @param int $page
     * @功能说明:后台下单列表
     * @author chenniang
     * @DataTime: 2022-02-16 14:05
     */
    public function adminDataSelect($dis){

        $data = $this->alias('a')
            ->join('lbfarm_order_address b','a.id = b.order_id AND b.type=1','left')
            ->where($dis)
            ->field('a.*,b.user_name,b.mobile')
            ->group('a.id')
            ->order('a.id desc')
            ->select()
            ->toArray();

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-28 15:05
     * @功能说明:添加商品时溯源下拉框
     */
    public function goodsSourceSelect($user_id){

        $dis[] = ['a.user_id','=',$user_id];

        $dis[] = ['a.pay_type','>',1];

        $order_source = $this->alias('a')
                        ->join('lbfarm_land_order_seed b','a.id = b.order_id')
                        ->where($dis)
                        ->column('source_id');

        $source_model = new Source();

        $where[] = ['user_id','=',$user_id];

        $where[] = ['status','in',[2,3]];

        $where[] = ['type','=',1];

        $farmer_model = new Farmer();
        //如果自己是农场主
        $farmer_id = $farmer_model->where($where)->value('id');

        if(!empty($farmer_id)){

            $dis = [

                'farmer_id' => $farmer_id,

                'status'    => 1

            ];

            $source = $source_model->where($dis)->column('id');

            $order_source = array_merge($order_source,$source);
        }

        return $order_source;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-09 17:45
     * @功能说明:土地到期提醒
     */
    public function landOverService($uniacid){
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $tmpl       = $tmpl_model->dataInfo(['uniacid'=>$uniacid,'tmpl_name'=>'land_over']);

        $push_model = new PushMsgModel($uniacid);

        $dis[] = ['pay_type','>',1];

        $dis[] = ['have_notice','=',0];

        $dis[] = ['end_time','<',time()+10*86400];

        $list = $this->where($dis)->select()->toArray();

        if(!empty($list)){

            foreach ($list as $value){

                $this->dataUpdate(['id'=>$value['id']],['have_notice'=>1]);

                if(!empty($tmpl)){

                    $this->overService($value,$tmpl);
                }

                $push_model->sendMsg($value,9);

            }

        }

        return true;
    }









    /**
     * @author chenniang
     * @DataTime: 2019-12-27 19:19
     * @功能说明:发送订阅消息
     */
    public function overService($order,$tmpl){

        $this->dataUpdate(['id'=>$order['id']],['have_notice'=>1]);

        $user_model = new User();
        //获取用户的open_id
        $openid = $user_model->where(['id'=>$order['user_id']])->value('openid');
        //访问页面
        $page = 'land/pages/order/detail?id='.$order['id'].'&notice=1';
        //模版id
        $tmpl_id = $tmpl['tmpl_id'];
        //模版类容
        $service_model = new WxTmpl($order['uniacid']);
        //模版的key
        $key_worlds    = $service_model::getTmplKey($tmpl_id);

        if(!empty($openid)&&!empty($tmpl_id)&&!empty($key_worlds)){
            //验证模版内容
            if(!is_array($key_worlds)||count($key_worlds)<4){

                return true;
            }
            //发送内容
            $send_data = array(

                $key_worlds[1]=>array(
                    //商品名称
                    'value'=> $order['goods_name'],
                ),
                $key_worlds[2]=>array(
                    //到期时间
                    'value'=> date('Y-m-d H:i',$order['end_time']),
                ),
                $key_worlds[3]=>array(
                    //商品价格
                    'value'=>$order['order_code'],
                ),
                $key_worlds[4]=>array(
                    //支付金额
                    'value'=> '你的土地将到期，请注意管理',
                )
            );
            //模版消息库类
            $tmpl_sever = new WxTmpl($order['uniacid']);
            //发送模版消息
            $res = $tmpl_sever::sendTmpl($openid,$tmpl_id,$send_data,$page);

        }

        return true;
    }









}